'use strict';

define(['angular','common','u2frame'], function (angular,common) {
//    	console.log('主控制器controllers被加载！');
    var controllers = angular.module('app.controllers', ['app.u2frame']);
    
//  controllers.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
//      $ocLazyLoadProvider.config({
//          jsLoader: requirejs,
//          debug: false
//      });
//  }]);
   
	//主控制器结束
	controllers.controller('appCtrl', [ '$rootScope', '$scope', 'BizData', 'OssEndpoint', '$q'
	                         , function ($rootScope, $scope, BizData, OssEndpoint, $q ) {
	
	    var Model = this;
	    
	    //自定义required数据的背景色
	    $rootScope.requiredColor = {"background-color":"yellow"};
	    
		//定义报告根路径
		$rootScope.REPORT_URL = OssEndpoint.REPORT_URL;
		
	    if($(window).width()<768){
			$rootScope.deviceSmall = true;
		}else{
			$rootScope.deviceSmall = false;
	    }
		

		//////////////////////////显示或者隐藏左侧菜单/////////////////////
	    $scope.showLeftClick= function(){
	    	$scope.showLeft = !$scope.showLeft;
	    	//触发窗口resize事件
	    	//$(window).resize();
	    	$scope.showLeft2 = !$scope.showLeft2;
	    }
	    
	    if($rootScope.deviceSmall){
	    	$scope.showLeft = false;
		}else{
	    	$scope.showLeft = true;
	    	$scope.showLeft2 = false;
	    }

	    $scope.leftClick= function(){
//    	                     	    	alert('');
	    	if($(window).width()<768){
		    	$scope.showLeft = false;
			}
	    }

	    /////////////////////////////////////////////////////////////////
		
		//AppConfigParams
		//获取应用配置信息（主要是api服务器的地址）
		var getAppConfigParams = function(){
			//async:异步调用参数，默认值为异步调用true
			//获取应用配置信息（主要是api服务器的地址）
			$.ajax({
	            type: "GET",
	            async : true,
	            url: $rootScope.getServiceName() + "/system/util/getAppConfigParams",
//	            data: "{}",
	            contentType: "application/json; charset=utf-8",
//	            dataType: "text",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
	            	console.log('$rootScope.appConfigParams-->',data);
	            	if(data){
	                	$rootScope.appConfigParams = data;
	            	}else{
	            		alert('获取应用配置信息时返回错误信息！');
	            	}
	            },
	            error: function (msg) {
	                alert('获取应用配置错误信息：'+msg.responseText);
	            }
	        });
		};

	    //初始化
		//获取应用配置信息（主要是api服务器的地址）
		//getAppConfigParams();
		////////////////////////////////////////////////////////////////
	
		//ngWYSWYG
		$rootScope.editorConfig = {
	            sanitize: false,
	            
	            ////////////////自定义///////////////////////////////////////
	            //存在企业文件夹中
	            upload_image_url: $rootScope.getServiceName() + '/baseinfo/fastdfsFiles/list/upload', //配置的上传图片的路由
	            images_upload_base_path: '',//'/ngWYSIWYG',//上传图片存放路径
	            images_upload_base_http: OssEndpoint.imgEndpointUrl,//上传图片存放服务器
	            height: 100,
	            /////////////////////////////////////////////////////////////
	
	            toolbar: [
	            { name: 'basicStyling', items: ['bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript', '-', 'leftAlign', 'centerAlign', 'rightAlign', 'blockJustify', '-'] },
	            { name: 'paragraph', items: ['orderedList', 'unorderedList', 'outdent', 'indent', '-'] },
	            { name: 'doers', items: ['removeFormatting', 'undo', 'redo', '-'] },
	            { name: 'colors', items: ['fontColor', 'backgroundColor', '-'] },
	            { name: 'links', items: ['image', 'hr', 'symbols', 'link', 'unlink', '-'] },
	            { name: 'tools', items: ['print', '-'] },
	            { name: 'styling', items: ['font', 'size', 'format'] },
	            ]
	        };
		
		$rootScope.api = {
	        scope: $scope,
	        insertImage: function() {
	        	
	            var deferred = $q.defer();
	//    	        $timeout(function() {
	        	
	        	var input_f = $('<input type="file" name="file" pattern="image/gif,image/jpeg,image/jpg,image/png" accept="image/gif,image/jpeg,image/jpg,image/png">');
	        	input_f.on('change', function () {
	        		var form = $("<form/>",
	        			{
	//    	            action: editor.settings.upload_image_url, //设置上传图片的路由，配置在初始化时
	                    style: 'display:none',
	                    method: 'post',
	                    enctype: 'multipart/form-data'
	                  }
	              );
	              form.append(input_f);
	              var file = input_f[0].files[0];
	              
	              //FileAPI
	           // Retrieve file list
	              
	              var fWidth = 0;
	              var fHeight = 0;
	              
	           // Get info of image file (FileAPI.exif.js included)
	              FileAPI.getInfo(file, function (err/**String*/, info/**Object*/){
	                  if( !err ){
	                	  //console.log(info); // { width: 800, height: 600, exif: {..} }
	                      fWidth = info.width;
	                      fHeight = info.height;
	                      var destDir = '/' + $rootScope.editorConfig.images_upload_base_path + '/ngWYSIWYG';
	                      
	                      var data = {'lastModified': file.lastModified, 'fileScale': fWidth+'X'+fHeight, 'destDir':destDir};
	                      //console.log('data-->',data);
	                      
	                      var xhr = FileAPI.upload({
	                          url: $rootScope.editorConfig.upload_image_url,//'/baseinfo/fastdfsFiles/list/upload',
	                          data: data,//{ 'session-id': 123 },
	                          files: { file: file },
	                          complete: function (err, xhr){
	//                                  console.log('err-->',err);
	//                                  console.log('xhr-->',xhr);
	                              if( !err ){
	//                                    var result = xhr.responseText;
	                                  // ...
	                                  var response = JSON.parse(xhr.responseText);
	                                  var src = response.groupName+'/'+response.remoteFileName;
	                                  src = $rootScope.editorConfig.images_upload_base_http +'/'+ src;
	//	                                  console.log('src-->',src);
	                            	  deferred.resolve('<img style="width: auto;" src="' + src + '">');
	                            	  //deferred.resolve('<a target="_blank" href="'+src+'"><img style="width:100%;" src="'+src+'"/></a>');
	                              }else{
	                            	  deferred.reject(null);
	//	                                  alert('文件上传错误！');
	                              }
	                          }
	                      });
	//                          console.log('xhr1-->',xhr);//这是一个异步结果
	                      
	                  }
	              });           
	             
	          });
	
	          input_f.click();
	        	
	//    	      var val = prompt('Enter image url', 'http://');
	
	//    	      }, 1000);
	            
	          return deferred.promise;
	        }
	    };	    
	
	
		//打开窗口（只知道appid，用于在订单中打开订单）
		$rootScope.menuPreClick = function(appid,winParams) {
			/*
			var params = {
					"id":appid
			}
			$.LoadingOverlay("show");
			$http.post('/backstage/sysInfo/getUrlByID',params)
			.success(function(data,status,headers,config){
	//			console.log('data-->',data);
				$.LoadingOverlay("hide");
				if(data.code==0){
					var url,name;
					url = data.url;
					name = data.name;
					$rootScope.menuClick(appid,url,name,winParams);
				}else{
					alert('单据信息不存在！');
				}
			}).error(function(data,status,headers,config){
				$.LoadingOverlay("hide");
				alert('获取数据失败！',data);
			});
			*/
			if(!appid){
				alert('id不能为空！');
				return;
			}
			
			$.LoadingOverlay("show");
			$.ajax({
	             type: "GET",
	             url: $rootScope.getServiceName() + "/system/sysInfo/getSysInfoUrlByID",
	             data: {"id":appid},
	             dataType: "json",
	             success: function(data){
	            	console.log('data-->',data);
	 				$.LoadingOverlay("hide");
	 				if(data.code==0){
	 					var url,name;
	 					url = data.url;
	 					name = data.name;
	 					$rootScope.menuClick(appid,url,name,winParams);
	 				}else{
	 					alert(data.msg);
	 				}
                  },error: function(XMLHttpRequest, textStatus, errorThrown){
                      //通常情况下textStatus和errorThrown只有其中一个包含信息
                      //this;   //调用本次ajax请求时传递的options参数
                	  $.LoadingOverlay("hide");
                	  alert("ajax调用失败！");
                  },complete:function(XMLHttpRequest, textStatus){
                      this;    //调用本次ajax请求时传递的options参数
                  }
	         });
			
		};
		
		//页面渲染完成事件（页面元素加载完成）
	    $scope.bodyInit = function(){
	    	//console.log('load!','页面渲染完成事件！');
			document.getElementById('loading').style.display = "none";
			document.getElementById('window').style.display = "";
			//console.log('ng初始化完成！');
	    };
	    
	    //一次性修改弹出菜单样式
	    $scope.topMenuStyle = function(){
	    	//var Lis=document.getElementsByTagName('li');
			var Lis=document.getElementsByClassName('topmenuli');
	    	//console.log('ng-repeat完成Lis-->>', Lis);
			for(i=0;i<Lis.length;i++){
				//console.log('i-->',i);
				Lis[i].i=i;
				Lis[i].onmouseover=function(){
					//this.className="lihover";
		            $(this).addClass("lihover");
					var h0=(this.i-1)*30+42;
					//console.log('h0-->',h0);
					var y=this.getElementsByTagName("div")[0].offsetHeight;
					//console.log('y-->',y);
					var h=this.getElementsByTagName("div")[0].style.top+y;
					if(h<h0){
						this.getElementsByTagName("div")[0].style.top=h0+"px";
					}
					if(y>550){
						this.getElementsByTagName("div")[0].style.top=50+"px";
					}
					
					//设置left
					var l=$(this).context.offsetWidth - 1;
					//console.log('$(this).context.offsetWidth-->',l);
					this.getElementsByTagName("div")[0].style.left=l+"px";
				}
				Lis[i].onmouseout=function(){
					$(this).removeClass("lihover");
				}
				////////////////////////////////////////
				Lis[i].onclick=function(){
					$(this).removeClass("lihover");
				}
				////////////////////////////////////////
			}
	    	
	    };
	    
	    //接收ne-repeat完成的广播
	    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
	    	//下面是在table render完成后执行的js
	    	$scope.topMenuStyle();
	    });       
	    
	    $scope.navTabsData = [
	                          {"label":"树形导航","active":true},{"label":"菜单导航","active":false}
	                          ];
	    $scope.navTabsClick = function(event){
	    	for(var i=0;i<2;i++){
	    		if($scope.navTabsData[i].label==event.label){
	    			//当前被选中
	    			$scope.navTabsData[i].active = true;
	    		}else{
	    			$scope.navTabsData[i].active = false;
	    		}
	    	}
	    };
		
	
		
		Model.treeRowClick = function(event){
//			console.log('Model.treeRowClick!-->>',event);
//			console.log('Model.treeRowClick!row-->>',$scope.dataSysInfo.rows[event.rowIndex]);
			//var systemKind = $scope.dataSysInfo.getValue('systemKind',event.rowID);
			//var systemName = $scope.dataSysInfo.getValue('systemName',event.rowID);
			var appid = $scope.dataSysInfo.rows[event.rowIndex].fID.value;
			var systemKind = $scope.dataSysInfo.rows[event.rowIndex].systemKind.value;
			var systemName = $scope.dataSysInfo.rows[event.rowIndex].systemName.value;
//			var systemFullName = $scope.dataSysInfo.rows[event.rowIndex].systemFullName.value;
			var absoluteUrl = $scope.dataSysInfo.rows[event.rowIndex].absoluteUrl.value;
	//		var winParams = '可以在sysinfo表中增加参数列';
			//alert(systemKind);
			if(systemKind=='pag'){
				if(absoluteUrl){
					$rootScope.menuClick(appid,absoluteUrl,systemName);
					$scope.leftClick();
				}
			}
		};	
		
		Model.treeRowDblClick = function(event){
			//console.log('Model.treeRowDblClick!');
		};	
		
		Model.panelItemClick = function(event){
			//console.log('event-->',event);
			//var systemKind = $scope.dataSysInfo.getValue('systemKind',event.rowID);
			//var systemName = $scope.dataSysInfo.getValue('systemName',event.rowID);
	                 			
			var appid = event.fID.value;
			var systemKind = event.systemKind.value;
			var systemName = event.systemName.value;
			var absoluteUrl = event.absoluteUrl.value;
			//alert(systemKind);
			if(systemKind=='pag'){
				if(absoluteUrl){
					$rootScope.menuClick(appid,absoluteUrl,systemName);
					//$scope.leftClick();
				}
			}
			
		};	
		

	    Model.loadMenu=function(){
			
			var options = {};
			options.httpUrl = $rootScope.getServiceName();
			options.reader = '';//'/backstage/sysInfo/queryTreeNavigation';
			options.writer = '';
			options.deleter = '';
			options.idColumnDefine = "fID";
			options.idColumnName = "fID";
			options.defCols = {fID:{name:"fID",type:"String",label:""},systemCode:{name:"systemCode",type:"String",label:""},systemName:{name:"systemName",type:"String",label:""},systemFullID:{name:"systemFullID",type:"String",label:""},systemFullCode:{name:"systemFullCode",type:"String",label:""},systemFullName:{name:"systemFullName",type:"String",label:""},systemKind:{name:"systemKind",type:"String",label:""},systemDescribe:{name:"systemDescribe",type:"String",label:""},itemPrice:{name:"itemPrice",type:"Decimal",label:""},absoluteUrl:{name:"absoluteUrl",type:"String",label:""},nodeLevel:{name:"nodeLevel",type:"Integer",label:""},nodeKind:{name:"nodeKind",type:"String",label:""},sortNo:{name:"sortNo",type:"String",label:""},fParent:{name:"fParent",type:"String",label:""},status:{name:"status",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
			options.isTree = true;
			options.parentRelation = 'fParent';
			options.nodeKindRelation = 'nodeKind';
			options.nodeLevelRelation = 'nodeLevel';
			options.nodeSortRelation = "sortNo";
			options.pathRelation = 'systemFullID';
			options.directDeleteMode = true;
			options.limit = -1;
			options.orderBy = 'sortNo ASC';
			
			$scope.dataSysInfo = new BizData(options);
			
			$('#treeNavigation').LoadingOverlay("show");
			$scope.dataSysInfo.clearData();
			
			/*
			var params = {
			    "columns" : $scope.dataSysInfo.defCols,
			    "limit" : $scope.dataSysInfo.limit,
			    "offset" : 0,
			    "orderBy" : $scope.dataSysInfo.orderBy,
			};
			
			$.ajax({
		        type: "POST",
		        async : true,//异步请求
		        url: $rootScope.getServiceName() + '/sysInfo/queryTreeNavigation',
		        data: JSON.stringify(params),// "{}",
		        contentType: "application/json; charset=utf-8",
		        dataType: "json",
				success: function (data) {
					console.log('queryTreeNavigation.data-->',data);
					if(data.code==0){
						$scope.dataSysInfo.rows = data.data.rows;
						var appid = 'home';
						var url = '/center/center';
						var name = '首页';
						var winParams = '传递给窗口的参数！';
						$rootScope.menuClick(appid,url,name,winParams);
						$scope.$apply();
					}else if(data.code==1){
						$('#treeNavigation').LoadingOverlay("hide");
						alert('菜单为空！'+data.msg);
					}else{
						alert('加载菜单错误！'+data.msg);
					}
		        },error: function(XMLHttpRequest, textStatus, errorThrown){
					alert('ajax调用失败！');
		        },complete:function(XMLHttpRequest, textStatus){
					$('#treeNavigation').LoadingOverlay("hide");
		        }
		    });
			*/
			
			$.ajax({
		        type: "GET",
		        async : true,//异步请求
		        url: $rootScope.getServiceName() + '/sysInfo/getTreeMenu',
		        //data: "{}",
		        contentType: "application/json; charset=utf-8",
		        dataType: "json",
				success: function (data) {
					console.log('getTreeMenu.data-->',data);
					$('#treeNavigation').LoadingOverlay("hide");
					if(data.code==0){
						$scope.dataSysInfo.rows = data.data.rows;
//						var appid = 'home';
//						var url = '/center/center';
//						var name = '首页';
//						var winParams = '传递给窗口的参数！';
//						$rootScope.menuClick(appid,url,name,winParams);
						$rootScope.loadCenter();
						
						$scope.$apply();
					}else if(data.code==1){
						//alert('菜单为空！'+data.msg);
						
					}else{
						alert('加载菜单错误！'+data.msg);
					}
		        },error: function(XMLHttpRequest, textStatus, errorThrown){
					alert('ajax调用失败！');
		        },complete:function(XMLHttpRequest, textStatus){
					$('#treeNavigation').LoadingOverlay("hide");
		        }
		    });
			
			
	    };

	    //获取人员成员（后台授权）
	    Model.grant=function(psm){
			//console.log('Model.grant.psm-->',psm);
	    	var options = {
	    		"psm":psm
	    	}
	    	
			$('#treeNavigation').LoadingOverlay("show");
			$.ajax({
		        type: "POST",
		        async : true,//异步请求
		        url: $rootScope.getServiceName() + '/grant',
		        data: JSON.stringify(options),// "{}",
		        contentType: "application/json; charset=utf-8",
		        dataType: "json",
				success: function (data) {
					$('#treeNavigation').LoadingOverlay("hide");
					console.log('Model.grant.data-->',data);
					if(data.code==0){
						//获取成功
						$rootScope.dataPsm = data;
						
						
						$scope.$apply();
						Model.loadMenu();
						Model.hidePsmList();
					}else if(data.code==1){
						//存在多个人员成员，//请选择
						Model.getPsmList();
					}else{
						//alert('加载人员成员错误！'+data.msg);
					}
		        },error: function(XMLHttpRequest, textStatus, errorThrown){
					$('#treeNavigation').LoadingOverlay("hide");
					alert('ajax调用失败！');
		        }
		    });
	    };
	    
		//头部文件菜单的点击状态更改//////////////////////////////////////////////////
		
		/////////////////////////////////////////////////////////////////////////////////////
		
		
		/////////////////////////////////////////////////////////////////////////////////////
		
	    //下面为路由监控事件
		/*打开单据时未使用路由机制
	    //定义变量是为了关闭事件是调用
	    var locationChangeStartOff = $rootScope.$on('$locationChangeStart', locationChangeStart);  
	    var locationChangeSuccessOff = $rootScope.$on('$locationChangeSuccess', locationChangeSuccess);  
	
	    function locationChangeStart(oldState,newState) {  
	    };
	  
	    function locationChangeSuccess(oldState,newState) {
	    	//debugger;
	    	console.log('locationChangeSuccess-->',newState);
	    };
	    */
		
		//向下广播按键事件
		document.body.onkeyup=function(){
			$scope.$broadcast('document_keyup',event);
		}
	
		//加载人员成员
		Model.grant();
		
		Model.getPsmList = function (){

			$.ajax({
		        type: "GET",
		        async : true,
				url : $rootScope.getServiceName() + '/getPsmList',
				//data: JSON.stringify(options),// "{}",
		        contentType: "application/json; charset=utf-8",
		        dataType: "json",
		        success: function (data) {
		           	//console.log('getPsmList.success.query-->',data);
					$rootScope.dataPsms = data;
					Model.showPsmList();
					$scope.$apply();
		        },error: function(XMLHttpRequest, textStatus, errorThrown){
		        }
		    });

		};
		
		Model.showPsmList = function (){
			$scope.showPsmList=true;
		};
		
		Model.hidePsmList = function (){
			$scope.showPsmList=false;
		};


		
		
		
		//console.log('appCtrl控制器执行完成');
		return Model;
	
	}]);
	

    	
    return controllers;
    
 });